import React, { FC, useState } from "react";
import { Input } from "@/ui/Input/Input";
import { Button } from "@/ui/Button/Button";
import { useToken } from "@/store/auth";
import { login } from "@/api/auth";
import { Navigate } from "react-router-dom";
import { useUsers } from "@/api/users";
import cls from "../../styles/feature/LoginForm.module.scss";

const LoginForm: FC = () => {
  const [email, setEmail] = useState<string>("");
  const [password, setPassword] = useState<string>("");

  const { credentials, setCredentials } = useToken();

  const onLogin = async () => {
    try {
      const res = await login(email, password);
      setCredentials(res);
    } catch (e) {
      console.log({ error: e });
    }
  };

  return (
    <div className={cls.form}>
      {credentials && <Navigate to="/" replace />}
      <div className={cls.title}>Вход в профиль</div>
      <Input
        onChange={(e) => setEmail(e.currentTarget.value)}
        value={email}
        type="text"
        placeholder="Имя пользователя"
      />
      <Input
        onChange={(e) => setPassword(e.currentTarget.value)}
        value={password}
        type="password"
        placeholder="Пароль"
      />
      <Button type="submit" onClick={() => onLogin()}>
        Войти
      </Button>
    </div>
  );
};

export default LoginForm;
